package com.github.tyc1210.config;

import com.github.tyc1210.common.DynamicDataSourceConstant;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


public class DynamicDataSource extends AbstractRoutingDataSource {
//    @Autowired
//    private DataSource dataSource1;
//
//    @Autowired
//    private DataSource dataSource2;
//
//    // 配置所有数据源与默认数据源
//    @Override
//    public void afterPropertiesSet() {
//        // 为 targetDataSources 设置所有数据源
//        Map<Object,Object> all = new HashMap<>();
//        all.put("master",dataSource1);
//        all.put("slave",dataSource2);
//        super.setTargetDataSources(all);
//        // 为 defaultTargetDataSource 设置默认数据源，根据key找不到就用默认的
//        super.setDefaultTargetDataSource(dataSource1);
//        // 复制上述目标数据源给resolvedDataSources&resolvedDefaultDataSource
//        super.afterPropertiesSet();
//    }
//

    @Override
    public Connection getConnection() throws SQLException {
        CustomConnection customConnection = new CustomConnection(getCurDataSource().getConnection());
        if(TransactionContext.isOpenTran()){
            customConnection.setAutoCommit(false);
            DynamicContextHolder.MULTI_TRAN_CONNECTION.get().add(customConnection);
        }
        return customConnection;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        CustomConnection customConnection = new CustomConnection(getCurDataSource().getConnection(username, password));
        if(TransactionContext.isOpenTran()){
            customConnection.setAutoCommit(false);
            DynamicContextHolder.MULTI_TRAN_CONNECTION.get().add(customConnection);
        }
        return customConnection;
    }


    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicContextHolder.getKey();
    }

    private DataSource  getCurDataSource(){
        String key = DynamicContextHolder.getKey();
        DataSource dataSource;
        dataSource = DynamicContextHolder.getThreadDataSources(key);
        if(null == dataSource){
            /**
             * 容器启动时获取数据源 此时 key 为默认值 "" 获取不到数据源，返回默认数据源
             */
            dataSource = DynamicContextHolder.getThreadDataSources(DynamicDataSourceConstant.DEFAULT_KEY);
        }
        return dataSource;
    }
}
